local db = require("db")
local pairs = pairs
local ipairs = ipairs

module("units")

local units = db.units
local vunits = db.vunits
local races = db.races
local classes = db.classes
local factions = db.factions
local xpvalues = db.xp

function InitUnitsAuras()
	local auras = db.get("auras")
	for _, a in pairs(auras) do
		local unit = units[a.unit]
		if unit then
			local auras = unit.auras
			if not auras then
				auras = {}
				unit.auras = auras
			end
			local aura = {}
			for k, v in pairs(a) do
				if k ~= "unit" then
					aura[k] = v
				end
			end
			auras[#auras + 1] = aura
		end
	end
end

function GetBuffIndex(unit, index, filter)
	local auras = unit.auras
	if not auras or index < 1 then return end
	for i, aura in ipairs(auras) do
		if aura.type == filter then
			index = index - 1
			if index == 0 then
				return i
			end
		end
	end
end

function ResolveUnit(unitid)
	if not unitid then return end
	local id = vunits[unitid]
	if not id then
		if unitid:sub(-6) == "target" then
			local base = unitid:sub(1, -7)
			if base == "" then base = "player" end
			local bid = ResolveUnit(base)
			if bid and bid.target ~= "none" then
				return units[bid.target]
			end
		end
		return
	end
	return units[id.name]
end

function GetRaceInfo(race)
	if race then
		return races[race]
	end
end

function GetClassInfo(class)
	if class then
		return classes[class]
	end
end

function GetFactionInfo(faction)
	if faction then
		return factions[faction]
	end
end

function GetXPToLevel(level)
	return xpvalues[level] and xpvalues[level] or 800000
end
